import app from '../App.vue';
import cookie from "@/utils/cookie";
import { router } from "@/utils";
const http = (options) => {
    return new Promise((resolve, reject) => {
        // uni.showLoading({
        //     title: '加载中...',
        //     mask: options.load || false // 默认遮罩出现可以继续操作
        // });
        try{
            uni.request({
                url: (options.baseURL || app.globalData.baseURL) + options.url,
                method: options.method || 'POST', // 默认为POST请求
                data: options.data, //请求超时在manifest.json配置
				timeout: 10000,
                header: {
                    'token': options.token?options.token:cookie.get('token')?cookie.get('token'):'',
                    'Content-Type': options.header == 'form' ? 'application/x-www-form-urlencoded' : 'application/json',
					'time': Date.parse(new Date())
                },
                success: res => {
					if(res.statusCode===200){
						if(res.data.code===0){
							resolve(res.data.data);
						}else if(res.data.code===401){
							reject(res.data);
							if(options.url=='shopServer/prize/getList'){
								cookie.set('redirect', '/pagesnew/free/list')
							}
							if(options.url!=='shopServer/redBag/getUnReadRedBagTotalAmount'){
								router.reLaunch({
									path: '/pages/index/login'
								});
							}
						}else{
							reject(res.data.data);
							setTimeout(function() {
								uni.showToast({
									title: res.data.message?res.data.message:'服务器无返回',
									icon:'none',
									duration: 2000
								})
								setTimeout(function() {
									uni.hideToast();
								}, 2000);
							}, 100);
						}
					}else{
						setTimeout(function() {
							uni.showToast({
								title: res.data.message?res.data.message:'服务器无返回',
								icon:'none',
								duration: 2000
							})
							setTimeout(function() {
								uni.hideToast();
							}, 2000);
						}, 100);
					}
                },
                fail: (err) => {
                    reject(err.data);
                    console.log(err.data);
                    uni.showToast({
                        title: '服务器异常',
                        icon: 'none'
                    })
                },
                complete: () => {
                    // uni.hideLoading();
					uni.stopPullDownRefresh();
                }
            });
        }catch(e){
            // uni.hideLoading();
            uni.showToast({
                title: '请检查网络连接',
                icon: 'none'
            })
        }
        
    })
}

export default http